import React, { useEffect, useState } from "react";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import { Card, Table, Button, Popover, Radio, message, Popconfirm, Tag } from "antd";
import { withRouter } from "react-router-dom";
import AddNotice from './AddNotice'
import {
  noticeUpdateStatus,
  noticeInfo,
  noticeList,
  noticeDetele,
} from '@/api/api'
import "./index.scss";

let milCToken = {}
const NoticeManage = (props) => {
  // 面包屑
  const breadcrumbList = ["系统设置", "公告管理"];
  // 列表数据
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  // 添加公告显示隐藏控制
  const [addNoticeShow, setAddNoticeShow] = useState(false)
  // 添加或修改type
  const [type, setType] = useState('add')
  
  // 点击列表设置当前选中的数据
  const [currentItem, setCurrentItem] = useState({})
  // 状态
  const [statusShow, setStatusShow] = useState(false)
  const [statusIndex, setStatusIndex] = useState(null)
  // 删除
  const deleteNotice = async (row) => {
    try {
      let res = await noticeDetele({
        id: row.id
      })
      if(res.code === 0) {
        handleFinish()
        message.destroy()
        message.success('删除成功')
      }
    } catch (error) {
      console.log(error)
    }
  }
  const updateStatus = async (id, status) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await noticeUpdateStatus({ id, status  }, milCToken)
      if(res.code === 0) {
        message.success('操作成功')
        handleFinish()
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 获取列表
  const handleFinish = async () => {
    try {
      console.log(currentPage)
      let params = {
        pageSize,
        currentPage
      }
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }

      let res = await noticeList(params, milCToken)
      if(res.code === 0) {
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 表单结构
  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      align: "center",
      key: "title",
      render: (text, row, index) => text || "--",
    },
    {
      title: "内容",
      dataIndex: "content",
      align: "center",
      key: "content",
      render: (text, row, index) => text || "--",
    },
    {
      title: "会员端",
      dataIndex: "member",
      align: "center",
      key: "member",
      width: 150,
      render: (text, row, index) => (text===1?'通知':'不通知') || "--",
    },
    {
      title: "商户端",
      dataIndex: "merchant",
      align: "center",
      key: "merchant",
      width: 150,
      render: (text, row, index) => (text===1?'通知':'不通知') || "--",
    },
    {
      title: "创建时间",
      dataIndex: "createdTime",
      align: "center",
      key: "createdTime",
      width: 150,
      render: (text, row, index) => text || "--",
    },
    {
      title: '公告状态',
      dataIndex: 'status',
      align: 'center',
      key: 'status',
      width: 80,
      render: (text, row, index) => {
        return <>
          {
            <Tag color={text == 0 ? '#f5222d' : '#52c41a'}
              onClick={() => updateStatus(row.id, text == 1 ? 0 : 1)}
            >
              {text == 1 ? '启用' : '停用'}
            </Tag>
          }
        </>
      },
    },
    {
      title: "操作",
      dataIndex: "operated",
      align: "center",
      key: "operated",
      fixed: 'right',
      width: 150,
      render: (text, row, index) => {
        return (
          [
            <Button key="1" size="small" type='primary' style={{marginRight: 10}} onClick={() => {
              setCurrentItem(row)
              setAddNoticeShow(true)
              setType('edit')
            }}>编辑</Button>,
            <Popconfirm key="2" placement="bottom" title='确认删除该公告吗？' onConfirm={() => {
              deleteNotice(row, index)
            }} okText="确认" cancelText="取消">
              <Button size="small" type='primary'>删除</Button>
            </Popconfirm>
          ]
        );
      },
    },
  ];
  
  
  // 更新
  useEffect(() => {
    // 获取列表
    handleFinish()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize])
  return (
    <div className="manage-component">
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className="manage-main">
        <div className="table-box">
          <Card>
            <div className="table-btns">
              <Button type="primary" htmlType="button" onClick={() => {
                setAddNoticeShow(true)
                setType('add')
              }}>
                新增公告
              </Button>
            </div>
            <div className="table">
              <Table
                size="middle"
                bordered
                scroll={{ x: 1000 }}
                className="antd-table"
                dataSource={dataSource}
                rowKey={"id"}
                pagination={{
                  size: "default",
                  current: currentPage,
                  total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {
                    setCurrentPage(page);
                    setPageSize(pagesize);
                  },
                }}
                columns={columns}
              />
            </div>
          </Card>
        </div>
      </div>
      <AddNotice defaultType={currentItem.types} visible={addNoticeShow} type={type} setVisible={setAddNoticeShow} noticeItem={currentItem} reload={() => {
        handleFinish()
      }}/>
    </div>
  );
};
export default withRouter(NoticeManage);
